package com.itcast.mobileController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itcast.health.constant.MessageConstant;
import com.itcast.health.pojo.Result;
import com.itcast.health.pojo.Setmeal;
import com.itcast.service.SetmealMobileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.List;

/**
 * @author Gao
 * @version v1.0
 * @date 2019/11/23 20:19
 * @description
 **/
@RestController
@RequestMapping("setmeal")
public class SetmealMobileController {
    @Reference
    private SetmealMobileService setmealMobileService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 查询所有套餐数据
     *
     * @return
     */
    @RequestMapping("getSetmeal")
    public Result getMobilSetmeal() {

        Jedis resource = jedisPool.getResource();
        String allSetmeal = resource.get("AllSetmeal");
        List setmeals = JSON.parseObject(allSetmeal, List.class);
        if (setmeals == null || setmeals.size() == 0) {
            try {
                setmeals = setmealMobileService.findAll();
                resource.set("AllSetmeal", JSON.toJSONString(setmeals));
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL);
            }
        }
        return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, setmeals);

    }

    @RequestMapping("findById")
    public Result findById(Integer id) {
        Jedis resource = jedisPool.getResource();
        String SetmealStr = resource.get("Setmeal" + id);
        Setmeal setmeal = JSON.parseObject(SetmealStr, Setmeal.class);
        if (setmeal == null) {
            try {
                setmeal = setmealMobileService.findById(id);
                resource.set("Setmeal" + id, JSON.toJSONString(setmeal));
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "查询失败,请刷新页面");
            }
        }
        return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, setmeal);

    }
}